#include <iostream>
#include <string>
#include <time.h>
#include <list>

#include "sockets.hpp"

using namespace std;

void wait( int ms )
{
	int startTime = clock();
	while( startTime + ms > clock() );
}

int main(int argc, char** argv)
{
	try{
		
	initSockets();
		
	bool isHost;
	cout << "Type 1 if you want to host, 0 if you want to join:" << endl;
	cin >> isHost;
	
	if ( isHost ) // Host code:
	{
		
		int serverPort;
		cout << "Type the hosting port:" << endl;
		cin >> serverPort;
		TcpSocket server;
		server.listen(serverPort);
		
		bool quit = false;
		int counter = 10;
		list<TcpSocket> conns; // The connection list
		char recvBuffer[256]; // The recieve buffer :O!
		while (!quit)
		{
			if( server.waitForData(0) ) // Someone connected
			{
				NetAddress incommingaddr; // This will be written over with the address
				conns.push_back( server.accept( incommingaddr ) ); // Accept the connection
				cout << endl << "New Connection Spawned!" << endl;
			}
			
			for ( list<TcpSocket>::iterator iter = conns.begin(); iter != conns.end(); ++iter) // For each spawned connection:
			{
				if( iter->waitForData(0) ) // If this connection has some data waiting
				{
					int recvAmmount = iter->recv( recvBuffer, sizeof(recvBuffer) );
					cout << endl << "recieved data [" << recvAmmount << "]: " << string(recvBuffer, recvAmmount) << endl;
				}
			}
			wait(100); // Haxy wait, makes this loop 10 times per second.
			// this wait is haxy, it should be some system sleep thing but I cba
			
			if( counter > 0 ) // This is just for printing a dot once per second
			{
				counter--;
			}else
			{
				counter = 10;
				cout << '.';
			}
		}
	}else // Client code:
	{
		TcpSocket client;
		NetAddress svaddr;
		int serverPort;
		string svName;
		cout << "Type the server domain name (could be an ip):" << endl;
		cin >> svName;
		cout << "Type the server port:" << endl;
		cin >> serverPort;
		svaddr.resolve( svName, 9898 );
		client.connect( svaddr );
		
		while ( client.isConnected() )
		{
			string inputtext;
			cin >> inputtext; // Get some text from the user
			client.send( inputtext.c_str(), inputtext.size()+1 ); // send it :O!
		}
		cout << "The connection was lost." << endl;
		
	}
	
	}catch( exception& e )
	{
		cout << e.what() << endl;
	}

	shutdownSockets();
	
	cin.ignore(10000000, '\n');

	return 0;
}
